| Conditions | 10 |
| Total Lines | 46 |
| Code Lines | 39 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
Complex classes like rewrite.ts ➔ rewrite often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
| 1 | import {promisify} from "util" |
||
| 11 | |||
| 12 | async function rewrite(filename: string, lines: string[], eol: string, checkMode: boolean) { |
||
| 13 | const {length} = lines |
||
| 14 | , fileExists = await $exists(filename) |
||
| 15 | |||
| 16 | if (fileExists) { |
||
| 17 | const lineReader = createInterface({ |
||
| 18 | input: createReadStream(filename), |
||
| 19 | crlfDelay: Infinity, |
||
| 20 | historySize: 0 |
||
| 21 | }) |
||
| 22 | |||
| 23 | let isSame = true |
||
| 24 | , row = 0 |
||
| 25 | |||
| 26 | for await (const line of lineReader) { |
||
| 27 | if (line !== lines[row]) { |
||
| 28 | isSame = false |
||
| 29 | break |
||
| 30 | } |
||
| 31 | row++ |
||
| 32 | } |
||
| 33 | |||
| 34 | lineReader.close() |
||
| 35 | |||
| 36 | if (isSame) { |
||
| 37 | if (lines[row] === "") |
||
| 38 | row++ |
||
| 39 | if (length === row) |
||
| 40 | return |
||
| 41 | } |
||
| 42 | } |
||
| 43 | |||
| 44 | if (checkMode) |
||
| 45 | throw Error(`Content of "${filename}" should be another`) |
||
| 46 | |||
| 47 | const fd = await $open(filename, "w") |
||
| 48 | |||
| 49 | for (let i = 0; i < length; i++) |
||
| 50 | await $write(fd, `${ |
||
| 51 | i ? eol : '' |
||
| 52 | }${ |
||
| 53 | lines[i] |
||
| 54 | }`) |
||
| 55 | |||
| 56 | await $close(fd) |
||
| 57 | } |
||
| 58 |